﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Common;

namespace DataAccess
{
    public class RatingsRepository : ConnectionClass
    {
        public RatingsRepository() : base() { }

        public decimal GetRatingForProduct(int productID)
        {
            decimal productRating = 0;

            try
            {
                productRating = (from r in entities.Ratings
                                 where r.Product_FK == productID
                                 select r.Rating1).Sum();
            }
            catch (InvalidOperationException IOE)
            {
                productRating = 0;
            }

            return productRating;
        }

        public void PlaceRating(Rating r)
        {
            try
            {
                entities.AddToRatings(r);
                entities.SaveChanges();
            }
            catch (Exception ex)
            {
                throw ex.InnerException;
            }
        }

        public int GetNoOfProductRates(int productID)
        {
            return entities.Ratings.Count(r => r.Product_FK == productID);
        }

        public decimal CalculateProductAvgRating(int productID)
        {
            decimal productRating = GetRatingForProduct(productID);
            int noofOfRatingForProduct = GetNoOfProductRates(productID);
            decimal avg = 0;

            if (productRating == 0 && noofOfRatingForProduct == 0)
            {
                avg = 0;
            }
            else
            {
                avg = productRating / noofOfRatingForProduct;
            }

            return avg;
        }

        public IEnumerable<RatingOption> GetRatingsOptions()
        {
            return entities.RatingOptions.AsQueryable();
        }
    }
}
